<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button v-permission="['超级管理员']" type="primary" icon="el-icon-plus" size="mini" @click="formVisible=true">
          充值额度
        </el-button>
        <el-button type="primary" size="mini"  @click="dialogVisible = true">申请教师名额</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="代理商/学校" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%" border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key" @sort-change="tableSortCge">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="agentName" label="代理商/学校"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="50" align="center" prop="teach_type" label="性质">
        <template slot-scope="scope">
          <span v-if="scope.row.teach_type==1">教师</span>
          <span v-else-if="scope.row.teach_type==4">观察员</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="100" align="center" prop="count" label="总额度"  sortable="custom">
      </el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="100" align="center" prop="use_count" label="已创建数">
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="100" align="center" prop="residue" label="剩余额度" ></el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="140" align="center" label="创建记录">
        <template slot-scope="scope">
          <el-link type="primary" @click="showDetail(scope.row)">查看</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openConsume(scope.row)">领用</el-button>
            <el-button v-permission="['超级管理员']" size="mini" type="primary" @click="openEdit(scope.row)">编辑
            </el-button>
            <el-button v-permission="['超级管理员']" size="mini" @click="delContent(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText"/>

    <el-dialog title="额度充值" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px">
        <el-form-item label="代理商:" label-width="130px" prop="agent">
          <el-select v-model="addForm.agent" filterable placeholder="请选择代理商" :disabled="editSubjects">
            <el-option
              v-for="item in agentArr"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别:" label-width="130px" prop="teachType">
          <el-select v-model="addForm.teachType" placeholder="请选择教师类别" :disabled="editSubjects">
            <el-option label="教师" :value="1"></el-option>
            <el-option label="观察员" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="editSubjects ? '额度:' : '充值数量:'" label-width="130px" prop="count">
          <el-input v-model="addForm.count" placeholder="请输入充值数量" type="number" min="0"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="editAccountLimit('ruleForm')" size="mini" round>确定
        </el-button>
        <el-button v-else type="primary" @click="addAccountLimitControl('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisible"  width="30%">
      <span>您好，单独申请教师名额，请联系您的业务经理或联系我司4006784158服务热线，目前暂不支持线上单独申请，谢谢！</span>
    </el-dialog>
  </div>
</template>

<script>
import objectable from "@/utils/objectable.js";
import dynamicTable from "@/components/DynamicTable/index";
import deleteDialog from "@/components/deleteDialog/index";
import tableMini from '@/utils/tableMini.js'
import {getAgentAndSchool, getBatchTwo} from "@/api/equipment";
import permission from "@/directive/permission";
import {addTeacherLimit, delTeacherLimit, editTeacherLimit, queryTeacherCount} from "@/api/teacher";

export default {
  mixins: [tableMini],
  components: {dynamicTable, deleteDialog},
  directives: {permission},
  data() {
    return {
      key: 1,
      colData: [], //动态控制table
      checkboxVal: ["ID", "代理商/学校", "性质", "总额度", "已创建数", "剩余额度", "创建记录"],
      searchTable: "",
      select: "", //搜索条件
      tableData: [],
      listQuery: {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
      },
      addForm: {
        agent: '',
        count: '',
        teachType: ''
      },
      formVisible: false,
      rules: {
        agent: [{required: true, message: '请选择代理商', trigger: 'change'}],
        teachType: [{required: true, message: '请选择教师类别', trigger: 'change'}],
        count: [{required: true, message: '请输入数量', trigger: 'blur'}],
      },
      editSubjects: false,
      deleteDialogs: {show: false, deleteText: '', deleteId: 0},
      batchArr: [],
      agentArr: [],
      dialogVisible: false,
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getAccountLimit()
    this.getBatchTwo()
    this.getAgentAndSchool()
  },
  methods: {
    Refresh() {
      this.listQuery = {startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
      this.getAccountLimit()
    },
    getBatchTwo() {
      getBatchTwo({userId: localStorage.getItem("ID")}).then(res => {
        this.batchArr = res.data
      }).catch(err => {
        this.batchArr = []
      })
    },
    getAgentAndSchool() {
      getAgentAndSchool({userId: localStorage.getItem("ID")}).then(res => {
        this.agentArr = res.data
      }).catch(err => {
        this.agentArr = []
      })
    },
    //搜索
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.agentName = this.searchTable
          this.getAccountLimit();
          break;
      }
    },
    openEdit(row) {
      this.formVisible = true
      this.editSubjects = true
      this.addForm = {
        agent: row.agent,
        teachType: row.teach_type,
        count: row.count,
        id: row.id
      }
    },
    editAccountLimit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let editForm = JSON.parse(JSON.stringify(this.addForm))
          editForm.last_ip = sessionStorage.getItem("Ip")
          editForm.userId = localStorage.getItem("ID")
          editTeacherLimit(editForm).then(res => {
            this.$message.success(res.msg)
            this.getAccountLimit()
            this.formVisible = false
            this.editSubjects = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });
    },
    addAccountLimitControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addTeacherLimit(addForm).then(res => {
            this.$message.success(res.msg)
            this.getAccountLimit()
            this.formVisible = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });
    },
    getAccountLimit() {
      queryTeacherCount(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    delContent(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    showDetail(row) {
      this.$router.push({name: 'supervisors', query: {adminName: row.agentName, teacherType: row.teach_type}});
    },
    openConsume(row) {
      this.$router.push({name: 'supervisorsAdd', query: {teach_type: row.teach_type, isEdit: 0, agentId: row.agent}})
    },
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId,
      }
      delTeacherLimit(params).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
        this.getAccountLimit()
      }).catch(err => {
        console.log("请求失败", err)
      })
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getAccountLimit()
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getAccountLimit()
    },
    //表格排序事件
    tableSortCge(column) {
      let order = ''
      column.order == "descending" ? order = 'desc' : order = 'asc'
      let sort = [{ field: column.prop, sort: order }]
      this.listQuery.sort = JSON.stringify(sort)
      this.getAccountLimit()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.editSubjects = false
      this.$nextTick(() => {
        this.addForm = this.$options.data().addForm
      })
    },
  }
}
</script>

<style scoped>

</style>


